provider "alicloud" {
  region = var.region
}

//根据资源组名称查询资源组
data "alicloud_resource_manager_resource_groups" "rmrg" {
  name_regex = var.resource_group_id
}

//根据资源组id查询vpc
data "alicloud_vpcs" "vpcs2" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//根据资源组id查询vswitch
data "alicloud_vswitches" "vsws" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//根据vpc id查询安全组
data "alicloud_security_groups" "sgs" {
  vpc_id = data.alicloud_vpcs.vpcs2.vpcs.0.id
}

resource "alicloud_instance" "instance" {
  count                = var.instance_number
  availability_zone = var.availability_zone
  # alicloud_security_group.default.*.id 安全组id
  security_groups = data.alicloud_security_groups.sgs.groups.*.id
  instance_type        = var.instance_type
  system_disk_category = "cloud_efficiency"
  system_disk_size     = var.disk_size
  image_id             = var.image_id
  instance_name        = var.app_name
  vswitch_id = data.alicloud_vswitches.vsws.vswitches.0.id
  # 设置带宽大于1， 则自动分配公网IP
  key_name   = var.ssh_key_name
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

resource "ansible_host" "middleware" {
  count                = var.instance_number
  inventory_hostname = var.bandwidth_out >= 1 ? alicloud_instance.instance[count.index].public_ip : alicloud_instance.instance[count.index].private_ip
  groups             = [format("%s",var.app_name)]
  vars = {
      wait_connection_timeout = 600
      public_ip = alicloud_instance.instance[count.index].public_ip
      private_ip = alicloud_instance.instance[count.index].private_ip
    }
}